package dk.eclipse.android.badassapp.camera;
/**
 * 
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import dk.eclipse.android.badassapp.R;
import dk.eclipse.android.badassapp.preferences.PreferenceHelper;
import dk.eclipse.android.badassapp.sms.SMSCommandoActivity;

/**
 * This class presents the user interface for the intelligence tab.
 * 
 * @author Ronni Kahalani (eclipse.dk)
 * 
 */
public class IntelligenceActivity extends Activity {
	/**
	 * Tag used for logging information.
	 */
	private static final String LOG_TAG = IntelligenceActivity.class
			.getSimpleName();

	private static final String SEND_SUBJECT = "Intelligence from: {0}";
	private static final String SEND_BODY = "You have recieved new intelligence, please look at the attached file.";
	private static final String SEND_MIMETYPE_TEXT = "text/plain";

	/**
	 * Intent request codes for the startActivityForResult()
	 */
	private static final int RECQUEST_CAMERA_IMAGE = 1;
	private static final int REQUEST_CAMERA_VIDEO = 2;
	protected static final int REQUEST_EMAIL = 10;

	/**
	 * The filenames of the output video and image files.
	 */
	private static final String FILE_CAMERA_IMAGE = "camera_image.jpg";
	private static final String FILE_CAMERA_VIDEO = "camera_video.3gp";

	/**
	 * Image and video files and uri's.
	 */
	private static final String path = Environment
			.getExternalStorageDirectory().toString();
	private static final File imageFile = new File(path, FILE_CAMERA_IMAGE);
	private static final Uri imageUri = Uri.fromFile(imageFile);
	private static final File videoFile = new File(path, FILE_CAMERA_VIDEO);
	private static final Uri videoUri = Uri.fromFile(videoFile);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.intelligence);
		setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.ic_app);

		ImageView headerImageView = (ImageView) findViewById(R.id.intelligenceHeader);
		headerImageView.setImageResource(R.drawable.intelligence_header);

		ImageButton sendVideoButton = (ImageButton) findViewById(R.id.sendVideoButton);
		sendVideoButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				sendVideo();
			}
		});

		ImageButton sendImageButton = (ImageButton) findViewById(R.id.sendImageButton);
		sendImageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				sendImage();
			}

		});

		ImageButton sendSMSButton = (ImageButton) findViewById(R.id.sendSMSButton);
		sendSMSButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				sendSMS();
			}
		});

		TextView sendSMSTextView = (TextView) findViewById(R.id.sendSMSTextView);
		sendSMSTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendSMS();
			}
		});

		TextView sendImageTextView = (TextView) findViewById(R.id.sendImageTextView);
		sendImageTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendImage();
			}
		});

		TextView sendVideoTextView = (TextView) findViewById(R.id.sendVideoTextView);
		sendVideoTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendVideo();
			}
		});
	}

	/**
	 * Sends a SMS.
	 */
	protected void sendSMS() {
		Intent intent = new Intent(getApplicationContext(),
				SMSCommandoActivity.class);
		startActivity(intent);
	}

	/**
	 * Sends an image.
	 */
	private void sendImage() {
		// Create new file for the camera image.
		try {
			
			imageFile.createNewFile();
			
		} catch (IOException e) {
			Log.e(LOG_TAG, "Failed to create new file:" + imageFile.getAbsolutePath(), e);
		}

		// Start the image capture activity.
		Intent cameraIntent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				imageUri);
		startActivityForResult(cameraIntent, RECQUEST_CAMERA_IMAGE);
	}

	/**
	 * Send a video.
	 */
	protected void sendVideo() {
		Intent cameraIntent = new Intent(
				android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
		startActivityForResult(cameraIntent, REQUEST_CAMERA_VIDEO);
	}

	/**
	 * Writes a video stream to file.
	 * 
	 * @param fis
	 * @param fileTo
	 * @throws IOException
	 */
	public static void writeVideo(FileInputStream fis, File fileTo)
			throws IOException {

		InputStream inBuffer = null;
		OutputStream outBuffer = null;
		byte[] buffer = new byte[1024];

		try {

			inBuffer = new BufferedInputStream(fis);
			OutputStream out = new FileOutputStream(fileTo);
			outBuffer = new BufferedOutputStream(out);

			int bytesRead = 0;

			// Keep reading from the file while there is any content
			// when the end of the stream has been reached, -1 is returned
			while ((bytesRead = inBuffer.read(buffer)) != -1) {
				out.write(buffer);
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {

			if (inBuffer != null) {
				inBuffer.close();
			}
			if (outBuffer != null) {
				outBuffer.close();
			}
		}
	}

	/**
	 * Send media (image or video) via a send action intent.
	 * 
	 * @param uri
	 */
	private void sendMedia(Uri uri) {

		Intent msg = new Intent(Intent.ACTION_SEND);
		msg.setType(SEND_MIMETYPE_TEXT);
		msg.putExtra(Intent.EXTRA_EMAIL, new String[] { PreferenceHelper
				.getIntelligenceEmail(getApplicationContext()) });
		msg.putExtra(Intent.EXTRA_TEXT, SEND_BODY);
		msg.putExtra(Intent.EXTRA_SUBJECT, MessageFormat.format(SEND_SUBJECT,
				PreferenceHelper.getFighterName(getApplicationContext())));

		// Add the media file location.
		msg.putExtra(Intent.EXTRA_STREAM, uri);

		// Start the send activity, with a chooser, if multiple activities can
		// handle the send action intent.
		startActivity(Intent.createChooser(msg, "Send via"));
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == REQUEST_CAMERA_VIDEO) {
			if (resultCode == Activity.RESULT_OK) {
				try {

					AssetFileDescriptor videoAsset = getContentResolver()
							.openAssetFileDescriptor(data.getData(), "r");
					FileInputStream in = videoAsset.createInputStream();
					writeVideo(in, videoFile);
					sendMedia(videoUri);

				} catch (IOException e) {

					Toast.makeText(
							getBaseContext(),
							"Could not find video file: "
									+ videoFile.getAbsolutePath(),
							Toast.LENGTH_LONG).show();
				}

			}
		} else if (requestCode == RECQUEST_CAMERA_IMAGE) {
			if (resultCode == Activity.RESULT_OK) {

				String fileName = imageFile.getName();

				// Make a thumb nail and put add it to the media store.
				try {
					MediaStore.Images.Media.insertImage(getContentResolver(),
							imageFile.getAbsolutePath(), fileName, fileName);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}

				// Send the image.
				sendMedia(imageUri);
			}
		}
	}

}
